package me.youline.dataServer.service.pubMsg;

import java.io.InputStream;
import java.util.Collections;
import java.util.List;

import me.youline.dataServer.controller.dto.PubMsgPostDTO;
import me.youline.dataServer.dao.PubMsgIndexDAO;
import me.youline.dataServer.entity.PublicMessage;
import me.youline.dataServer.entity.PublicMessageIndex;
import me.youline.dataServer.exception.PubMsgServiceException;
import me.youline.dataServer.exception.UnExistDataException;
import me.youline.dataServer.exception.UnPermitAccessException;
import me.youline.dataServer.service.pubMsg.PubMsgBuildService.PubMsgBuildContext;
import me.youline.dataServer.utils.IdPagination;

import org.perf4j.aop.Profiled;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

/**
 * 公告门面类
 * @author linhan
 *
 */
@Service
public class PublicMessageFacade {

	private static final Logger logger = LoggerFactory
			.getLogger(PublicMessageFacade.class);

	@Autowired
	private PubMsgIndexDAO publicMessageIndexDAO;

	@Autowired
	private PubMsgQueryService pubMsgQueryService;

	@Autowired
	public PubMsgUpdateService pubMsgUpdateService;
	
	@Autowired
	private PubMsgBuildService pubMsgBuildService;

	
	/**
	 * 发布公告消息
	 * 
	 * @param creatorId 创建人ID
	 * @param dto 提交的公告实体基本数据
	 * @param recognPicEntity 识别图实体
	 * @param displayPicEntity 效果图实体
	 * @return
	 * @throws PubMsgServiceException
	 */
	@Transactional(rollbackFor = Exception.class)
	@Profiled(tag = "service-创建原创消息", logFailuresSeparately = true)
	public PublicMessage buildOriginalPublicMessage(Long creatorId,
			PubMsgPostDTO dto, InputStream recognPicEntity, InputStream displayPicEntity)
			throws PubMsgServiceException {
		try {
			return pubMsgBuildService.buildOriginalPublicMessage(new PubMsgBuildContext(displayPicEntity,recognPicEntity,dto.getSceneId(),creatorId));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new PubMsgServiceException("创建消息业务执行失败");
		}
	}
	
	/**
	 * 获取广场公告列表
	 * @param page
	 * @return
	 */
	public List<PublicMessageIndex> getSquareMsgList(IdPagination page){
		return pubMsgQueryService.getAllMsgIndex(page);
	}

	

	/**
	 * 获取公告栏指定消息的详细数据
	 * 
	 * @param userId
	 * @param msgId
	 * @return
	 * @throws UnPermitAccessException
	 * @throws UnExistDataException
	 */
	public PublicMessage getPublicMessageDetailInfo(Long userId, Long msgId)
			throws UnPermitAccessException, UnExistDataException {
		PublicMessage msg = pubMsgQueryService.getPubMsgDetailInfo(msgId);
		if (msg == null) {
			throw new UnExistDataException("消息不存在");
		} else{
			return msg;
		}
	}

	/**
	 * 获取指定用户主页的公告列表
	 * 
	 * @param userId
	 * @param page
	 * @return
	 */
	@Transactional(readOnly = true)
	@Profiled(tag = "service-获取个人主页列表")
	public List<PublicMessageIndex> getPersonalHomepageMsgList(Long viewUserId,
			Long userId, IdPagination page) {
		List<PublicMessageIndex> list = pubMsgQueryService.getPersonalMsgIndex(viewUserId, userId, page);
		return list;
	}
	
	/**
	 * 删除公告消息
	 * 
	 * @param dto
	 * @throws UnExistDataException
	 * @throws UnPermitAccessException
	 */
	@Transactional(rollbackFor = Exception.class)
	@Profiled(tag = "service-删除消息")
	public void deletePublicMessage(Long messageId, Long processUserId)
			throws UnExistDataException, UnPermitAccessException {
		checkMsgUpdatePermission(messageId, processUserId);
		pubMsgUpdateService.deletePublicMessage(messageId, processUserId);
	}

	/**
	 * 根据消息ID，获取消息索引
	 * 
	 * @param msgId
	 * @return
	 */
	public PublicMessageIndex getMsgIndex(Long msgId) {
		return publicMessageIndexDAO.getIndexBymsgId(msgId);
	}


	/**
	 * 判断消息是否存在
	 * 
	 * @param msgId
	 * @return
	 */
	public boolean isMsgExist(Long msgId) {
		return publicMessageIndexDAO.getIndexBymsgId(msgId) != null;
	}
	
	/**
	 * 获取指定用户关注人公告列表
	 * @param userId
	 * @param page
	 * @return
	 */
	public List<PublicMessage> getFollowingMsgList(Long userId,IdPagination page){
		List<PublicMessageIndex> indexs = pubMsgQueryService.getFollowingMsgList(userId, page);
		if(indexs.isEmpty()){
			return Collections.emptyList();
		}
		List<Long> list = Lists.transform(indexs, new Function<PublicMessageIndex,Long>(){
			@Override
			public Long apply(PublicMessageIndex input) {
				return input.getMsgId();
			}
		});
		return pubMsgQueryService.getPubMsgDetailInfos(list);
	}

	/**
	 * 检验当前操作用户对消息是否有变更消息的权利，用户只能对自己创建和转发的消息执行操作
	 * 
	 * @param messageId
	 * @param processUserId
	 * @return
	 * @throws UnPermitAccessException
	 */
	private boolean checkMsgUpdatePermission(Long messageId, Long processUserId)
			throws UnPermitAccessException {
		PublicMessageIndex index = publicMessageIndexDAO
				.getIndexBymsgId(messageId);
		if (index != null && processUserId.equals(index.getCreatorId())) {
			return true;
		} else {
			throw new UnPermitAccessException("当前用户无权限操作此消息");
		}
	}

}
